#define _CRT_SECURE_NO_WARNINGS 1

#include"List.h"

LTNode* LTInit()
{
	LTNode* list = (LTNode*)malloc(sizeof(LTNode));
	list->data = 0;
	list->next = list;
	list->prev = list;
	return list;
}


LTNode* BuyLTNode(LTDataType x)
{
	LTNode* list = (LTNode*)malloc(sizeof(LTNode));
	list->data = x;
	list->next = NULL;
	list->prev = NULL;
	return list;
}

void LTPrint(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d <=> ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	/*assert(phead);
	LTNode* newNode = BuyLTNode(x);
	LTNode* tail = phead->prev;
	phead->prev = newNode;
	newNode->next = phead;
	tail->next = newNode;
	newNode->prev = tail;*/
	LTInsert(phead, x);
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next);
	/*LTNode* tail = phead->prev;
	LTNode* tailPrev = tail->prev;
	tailPrev->next = phead;
	phead->prev = tailPrev;
	free(tail);*/
	LTErase(phead->prev);
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	/*LTNode* cur = phead->next;
	LTNode* newNode = BuyLTNode(x);
	phead->next = newNode;
	newNode->prev = phead;
	cur->prev = newNode;
	newNode->next = cur;*/

	LTInsert(phead->next, x);

}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next);
	/*LTNode* cur = phead->next;
	LTNode* next = cur->next;
	phead->next = next;
	next->prev = phead;
	free(cur);*/
	LTErase(phead->next);
}

int LTSize(LTNode* phead)
{
	LTNode* cur = phead->next;
	int count = 0;
	while (cur != phead)
	{
		count++;
		cur = cur->next;
	}
	return count;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	LTNode* newNode = BuyLTNode(x);
	LTNode* posPrev = pos->prev;
	posPrev->next = newNode;
	newNode->prev = posPrev;
	pos->prev = newNode;
	newNode->next = pos;
}

void LTErase(LTNode* pos)
{
	LTNode* posPrev = pos->prev;
	LTNode* posNext = pos->next;
	posPrev->next = posNext;
	posNext->prev = posPrev;
	free(pos);
}